<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Cache;
use think\queue\connector\Redis;

class Task extends UserAuth{
    /**
     * 任务管理
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function index(){

        return $this->fetch('');
    }

    /**
     * 任务排序
     * @param id int id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function task_sort(){
        $data = $_POST;
        if(!isset($data['id'])){
            return show(config('code.error'),'id is not found！',[],404);
        }
        try{
            $save = Db::name('task')->where('id='.$data['id'])->update($data);

            if($save){
                return show(config('code.success'),'排序成功！');
            }else{
                return show(config('code.error'),'排序失败！');
            }
        }catch (\Exception $e){
            return show(config('code.error'),$e->getMessage(),[],500);
        }
    }

    /**
     * 任务列表
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function task_list(){
        $keywords = input('get.keywords');

        $where = ['task_name|task_url'
        => ['like', "%{$keywords}%"]];
        if(!empty($keywords)){

            $list = Db::name('task')->where($where)->order('sort asc')->select();

            $count = Db::name('task')->where($where)->count();

        }else{
            $list = Db::name('task')->order('sort asc')->select();

            $count = Db::name('task')->count();
        }

        $this->assign([
            'list' => $list,
            'count' => $count,
        ]);

        return $this->fetch('task_list');
    }

    /**
     * 新增任务
     * @param array $data
     * @return array|mixed|string|\think\response\Json
     */
    public function add_task(){
        if(request()->isAjax()){

            $data = $_POST;

            if(empty($data)){
                return show(config('code.error'),'数据不合法！',[],404);
            }

            //验证
            $validate = validate('task');

            if(!$validate->scene('add_task')->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            $add = Db::name('task')->insert($data);

            if($add){
                return show(config('code.success'),'新增成功！');
            }else{
                return show(config('code.error'),'新增失败！');
            }
        }

        return $this->fetch('add_task');
    }

    /**
     * 修改任务
     * @param id int id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|mixed|string|\think\response\Json
     */
    public function edit_task($id){
        $task = Db::name('task')->where('id='.$id)->find();

        if(request()->isAjax()){

            $data = $_POST;

            if(!isset($data['id'])){
                return show(config('code.error'),'id is not found！',[],404);
            }

            //验证
            $validate = validate('task');
            if(!$validate->scene('edit_task')->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            $update = Db::name('task')->where('id='.$data['id'])->update($data);

            if($update){
                return show(config('code.success'),'修改成功！');
            }else{
                return show(config('code.error'),'修改失败！');
            }
        }

        $this->assign('task',$task);

        return $this->fetch('edit_task');
    }

    /**
     * 删除任务
     * @param id int 任务id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function del_task(){
        $data = $_POST;

        if(!isset($data['id'])){
            return show(config('code.error'),'id is not found！',[],404);
        }

        $del = Db::name('task')->where('id='.$data['id'])->delete();

        if($del){
            return show(config('code.success'),'删除成功！');
        }else{
            return show(config('code.error'),'删除失败！');
        }
    }

    /**
     * 批量删除任务
     * @param id array 删除任务id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function batch_del_task(){
        $data = $_POST;

        if(!isset($data['id'])){
            return show(config('code.error'),'id is not found！',[],404);
        }

        $str = implode(',',$data['id']);

        $del = Db::name('task')->where("id in($str)")->delete();

        if($del){
            return show(config('code.success'),'批量删除成功！');
        }else{
            return show(config('code.error'),'批量删除失败！');
        }
    }

    /**
     * 任务执行失败错误提示信息（测试）
     * @param id int 用户id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function task_error()
    {
        //dump(LOG_PATH.'task');exit;
        $dir = LOG_PATH . 'task';
        $file = LOG_PATH . 'task/task.log';
        if (!is_dir($dir)) {
            mkdir($dir, 0777);
        }
        if (!is_file($file)) {
            $my_file = fopen($file, 'w');
            fclose($my_file);
        }

        //$my_file = fopen($file, "r") or die("不能打开文件");
        //$error = fread($my_file,filesize($file));
        //file_put_contents($file,'sssss'.PHP_EOL);
        //写入文件并且换行
        //file_put_contents($file,'xxxx'.PHP_EOL,FILE_APPEND);
        $error = file_get_contents($file);
        //$array = explode("\r\n",$error);//显示日志行数
        $sql_file = LOG_PATH . 'task/young5.sql';
        //$sql = str_replace(array("\r\n", "\r", "\n"), "", file_get_contents($sql_file));
        $sql = file_get_contents($sql_file);//把SQL语句以字符串读入$sql

        //通过sql语法的语句分割符进行分割
        $segment = explode(";", trim($sql));

        //var_dump($segment);
        $commenter = array('#', '--');
        //去掉注释和多余的空行
        foreach ($segment as & $statement) {
            $sentence = explode("\n", $statement);

            $newStatement = array();

            foreach ($sentence as $subSentence) {
                if ('' != trim($subSentence)) {
                    //判断是会否是注释
                    $isComment = false;
                    foreach ($commenter as $comer) {
                        if (eregi("^(" . $comer . ")", trim($subSentence))) {
                            $isComment = true;
                            break;
                        }
                    }
                    //如果不是注释，则认为是sql语句
                    if (!$isComment)
                        $newStatement[] = $subSentence;
                }
            }

            $statement = $newStatement;


            dump($statement);
            exit;

            dump($error);
            //dump($array);

            $this->assign('error', $error);
            $this->fetch('task_error');
        }
    }

    /**
     * 长期任务完成次数自增，自动结算任务
     */
    public function task_increment(){
        //插入任务完成时间、完成状态1
        $data = [
            'task_end_time' => time(),
            'task_status' => 1
        ];
        //模块名称
        $module = strtolower(request()->module());
        //控制器名称
        $controller = strtolower(request()->controller());
        //方法名称
        $action = strtolower(request()->action());
        $str = "$module/$controller/$action";
        $task = Db::name('task')
            ->where('task_url="'.$str.'"')
            ->field('id,task_end_time')
            ->find();
        if(!empty($task)){
            $time = Db::name('task')
                ->where('id='.$task['id'])
                ->field('task_end_time')
                ->find();
            if(date('Y-m-d') != date('Y-m-d',$time['task_end_time'])){
                //次数自增
                Db::name('task')
                    ->where('id='.$task['id'])
                    ->setInc('task_times');
            }
            Db::name('task')
                ->where('id='.$task['id'])
                ->update($data);
        }
    }

}
